package com.mz.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mz.demo.dao.LoginMapper;
import com.mz.demo.entity.SysUser;
import com.mz.demo.entity.vo.AccountPasswordInfoVo;
import com.mz.demo.entity.vo.LoginResVo;
import com.mz.demo.service.LoginService;
import com.mz.demo.utils.entity.GloableException;
import com.mz.demo.utils.entity.LoginUser;
import com.mz.demo.utils.tools.JWTUtils;
import com.mz.demo.utils.tools.RedisCache;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {


    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisCache redisCache;

    @Resource
    private LoginMapper loginMapper;

    @Override
    public LoginResVo loginByAccountPassword(AccountPasswordInfoVo accountPasswordInfoVo) {

        //1、判断账号密码是否匹配
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken( accountPasswordInfoVo.getUsername(), accountPasswordInfoVo.getPassword() );
        Authentication authentication = authenticationManager.authenticate( authenticationToken  );
        if( authentication == null ){
            throw GloableException.gen(10002, "帐号或密码错误");
        }

        //如果不为空，则从 authentication 中获取用户信息
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        SysUser sysUser = loginUser.getSysUser();
        System.out.println("loginUser: "+loginUser);
        //2、如果匹配成功，那么生成 jwt，并获取对应的用户信息。

        redisCache.setCacheObject("login:"+sysUser.getId(),loginUser);


        Map<String, Object> payload = new HashMap<>();
        payload.put("id", sysUser.getId());
        payload.put("username", sysUser.getUsername());
        String token = JWTUtils.getToken(payload);
        LoginResVo loginResVo = new LoginResVo( token, loginUser.getSysUser() );

        return loginResVo;
    }
}
